# 获取协程的返回值
import asyncio
import time
from functools import partial

loop = asyncio.get_event_loop()
start_time = time.time()


async def get_html(url):
    print("start request url: {} and get html".format(url))
    await asyncio.sleep(2)
    return "hello world"


def callback(url, future):
    result = future.result()
    print("finish request url, start handler url: {} this response content is {}".format(url, result))
    detail_task = loop.create_task(get_detail_html(result))
    detail_task.add_done_callback(get_detail_html_callback)


async def get_detail_html(result):
    await asyncio.sleep(2)
    print("start request detail html")
    return result + " how are you?"


def get_detail_html_callback(future):
    if time.time() - start_time > 1:
        exception_value = 1 / 0
    print("get detail html content {} start parse detail html, return special value".format(future.result()))
    loop.close()


def exception_handler(loop, context):
    print('Exception handler called')


if __name__ == "__main__":
    loop.set_exception_handler(exception_handler)
    task_list = []
    for i in range(10):
        task = loop.create_task(get_html("http://www.imooc.com"))
        task.add_done_callback(partial(callback, "http://www.imooc.com"))
        task_list.append(task)
        # 开启无限循环，需要在异步函数中调用stop()使停止
    loop.run_forever()
    # loop.run_until_complete(asyncio.wait(task_list))
    # 关闭事件循环 可以维护一个task_list
    # loop.stop()
    #
    print("spend time is {}", time.time() - start_time)
